package com.yumo.kangchenjunga.log;

import java.time.LocalDate;
import java.time.ZoneOffset;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.querydsl.core.types.dsl.BooleanExpression;

@Service
public final class LogService {

	@Autowired
	private LogRepository repository;

	public void log(LogEntity log) {
		LogEntity.create(repository, log);
	}

	public Page<LogVo> search(Integer activityId, String opObject, String op, LocalDate startDate, LocalDate endDate,
			Pageable pageable) {
		QLogEntity log = QLogEntity.logEntity;
		BooleanExpression exp = log.id.gt(0);

		if (activityId != null) {
			exp = exp.and(log.activityId.eq(activityId));
		}

		if (opObject != null) {
			exp = exp.and(log.opObject.eq(opObject));
		}

		if (op != null) {
			exp = exp.and(log.op.eq(op));
		}

		if (startDate != null) {
			exp = exp.and(log.opTime.goe(startDate.atStartOfDay(ZoneOffset.UTC).toInstant()));
		}

		if (endDate != null) {
			exp = exp.and(log.opTime.lt(endDate.plusDays(1).atStartOfDay(ZoneOffset.UTC).toInstant()));
		}

		return repository.findAll(exp, pageable).map(this::convertEntityToVo);
	}

	private LogVo convertEntityToVo(LogEntity entity) {
		var vo = new LogVo();

		vo.op = entity.op;
		vo.opDetail = entity.opDetail;
		vo.opObject = entity.opObject;
		vo.opResult = entity.opResult;
		vo.opTime = entity.opTime;
		vo.opUserId = entity.opUserId;
		vo.opUsername = entity.opUsername;

		return vo;
	}

}
